/**
 * 
 */
package org.mspring.mlog.web.module.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.News;
import org.mspring.mlog.entity.NewsCatalog;
import org.mspring.mlog.entity.Post;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.search.engine.SearchEngine;
import org.mspring.mlog.search.task.LuceneIndexRebuilderTask;
import org.mspring.mlog.service.NewsCatalogService;
import org.mspring.mlog.service.NewsService;
import org.mspring.mlog.support.log.Log;
import org.mspring.mlog.web.query.NewsQueryCriterion;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.dao.support.Sort;
import org.mspring.platform.utils.SessionUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * @author Gao Youbo
 * @since 2013年6月28日
 */
@Widget
@RequestMapping("/admin/news")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class Admin_NewsWidget extends Admin_AbstractWidget {
    @Autowired
    private NewsCatalogService newsCatalogService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private SearchEngine searchEngine;
    @Autowired
    private LuceneIndexRebuilderTask luceneIndexRebuilderTask;

    @RequestMapping("/list")
    @Log
    public String list(@ModelAttribute Page<News> newsPage, @ModelAttribute News news, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (newsPage == null) {
            newsPage = new Page<News>();
        }
        if (newsPage.getSort() == null) {
            newsPage.setSort(new Sort("createTime", Sort.DESC));
        }
        // 默认查看已发布的文章
        if (news == null) {
            news = new News();
        }
        if (queryParams.get("status") == null || StringUtils.isBlank(queryParams.get("status").toString())) {
            news.setStatus(News.Status.PUBLISH);
            queryParams.put("status", Post.Status.PUBLISH);
        }

        newsPage = newsService.listPage(new NewsQueryCriterion(queryParams), newsPage);
        model.addAttribute("newsPage", newsPage);

        List<NewsCatalog> newsCatalogs = newsCatalogService.getAll();
        model.addAttribute("newsCatalogs", newsCatalogs);

        model.addAttribute("status", News.Status.getStatusMap());
        return "/admin/news/listNews";
    }

    @RequestMapping("/create")
    public String create(@ModelAttribute News news, HttpServletRequest request, HttpServletResponse response, Model model) {
        List<NewsCatalog> newsCatalogs = newsCatalogService.getAll();
        model.addAttribute("newsCatalogs", newsCatalogs);
        return "/admin/news/createNews";
    }

    @RequestMapping("/create/save")
    @Log
    public String create_save(@ModelAttribute News news, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (news.getCreateTime() == null) {
            news.setCreateTime(new Date());
        }
        news.setAuthor(SecurityUtils.getCurrentUser(request));
        newsService.save(news);
        return "redirect:/admin/news/list";
    }

    @RequestMapping("/edit")
    public String edit(@ModelAttribute News news, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (news == null || news.getId() == null) {
            Long id = SessionUtils.getAttrAsLong(request, "Admin_NewsWidget_edit_id");
            if (id != null) {
                news = new News(id);
            }
        }
        SessionUtils.setAttr(request, "Admin_NewsWidget_edit_id", news.getId());

        if (news == null || news.getId() == null) {
            return prompt(model, "请先选择要修改的资讯");
        }
        news = newsService.get(news.getId());
        model.addAttribute("news", news);

        List<NewsCatalog> newsCatalogs = newsCatalogService.getAll();
        model.addAttribute("newsCatalogs", newsCatalogs);
        return "/admin/news/editNews";
    }

    @RequestMapping("/edit/save")
    @Log
    public String edit_save(@ModelAttribute News news, HttpServletRequest request, HttpServletResponse response, Model model) {
        newsService.update(news);
        return "redirect:/admin/news/list";
    }

    @RequestMapping("/delete")
    @Log
    public String delete(@RequestParam(required = false) Long[] id, @ModelAttribute Page<News> newsPage, @ModelAttribute News news, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (id != null && id.length > 0) {
            newsService.remove(id);
        }
        return list(newsPage, news, queryParams, request, response, model);
    }

    @RequestMapping("/autosave")
    @ResponseBody
    public String autosave(@ModelAttribute News news, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = SecurityUtils.getCurrentUser(request);
        if (news.getAuthor() == null) {
            news.setAuthor(user);
        }
        if (StringUtils.isBlank(news.getTitle())) {
            news.setTitle("无标题");
        }
        if (news.getCatalog() != null && StringUtils.isBlank(news.getCatalog().getName())) {
            news.setCatalog(null);
        }
        news.setStatus(News.Status.DRAFT);
        news = newsService.merge(news);
        return news.getId().toString();
    }

    @RequestMapping("/config")
    public String config(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "/admin/news/config";
    }

    /**
     * 更新文章索引
     * 
     * @return
     */
    @RequestMapping("/config/updateindex")
    @ResponseBody
    @Log(action = "更新新闻索引")
    public ResponseEntity config_updateindex() {
        ResponseEntity rsp = new ResponseEntity();
        try {
            Map<Object, Object> context = new HashMap<Object, Object>();
            context.put("clazz", News.class);
            context.put("batch", 100);
            luceneIndexRebuilderTask.doAsyncTask(context);
            rsp.setSuccess(true);
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            rsp.setSuccess(false);
            rsp.setMessage("update news index failure!" + e.getMessage());
            return rsp;
        }
    }

    /**
     * 优化索引
     * 
     * @return
     */
    @RequestMapping("/config/optimizeindex")
    @ResponseBody
    @Log(action = "优化新闻索引")
    public ResponseEntity config_optimizeindex() {
        ResponseEntity rsp = new ResponseEntity();
        try {
            searchEngine.optimize(News.class);
            rsp.setSuccess(true);
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            rsp.setSuccess(false);
            rsp.setMessage("optimize news index failure!" + e.getMessage());
            return rsp;
        }
    }
}
